package com.zx.platform.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by bibei on 2017/3/24.
 * 网络参数工具类
 */
public class HttpParamsUtils {
	public static String buildPayParams(Map<String, String> payParams){
		return buildPayParams(payParams,false,false);
	}

	/**
	 * @author
	 * @param payParams
	 * @return
	 */
	public static String buildPayParams(Map<String, String> payParams,boolean encoding){
	       return  buildPayParams(payParams,encoding,false);
	}

	public static String buildPayParams(Map<String, String> payParams,boolean encoding,boolean isSort){
		StringBuilder sb=new StringBuilder();
		List<String> keys = new ArrayList<String>(payParams.keySet());
		if(isSort) {
			Collections.sort(keys);
		}
		for(String key : keys){
			String value=payParams.get(key);
			if(StrUtils.isEmpty(value)){
				continue;
			}
			sb.append(key).append("=");
			if(encoding){
				sb.append(urlEncode(value));
			}else{
				sb.append(value);
			}
			sb.append("&");
		}
		sb.setLength(sb.length() - 1);
		return sb.toString();
	}

	public static String urlEncode(String str){
		try {
			return URLEncoder.encode(str, "UTF-8");
		} catch (Throwable e) {
			return str;
		}
	}

	/**
	 * 读取参数信息
	 * @param request
	 * @return
	 */
	public static  String getParameterStr(HttpServletRequest request) throws Exception{
		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader bufferedReader = null;
		InputStream inputStream = request.getInputStream();
		if (inputStream != null) {
			bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
			char[] charBuffer = new char[128];
			int bytesRead = -1;
			while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
				stringBuilder.append(charBuffer, 0, bytesRead);
			}
		} else {
			stringBuilder.append("");
		}
		return stringBuilder.toString();
	}
	
	/**
	 * 读取参数信息
	 * @param request
	 * @return
	 */
	public static Map<String,Object> getParameterMap(HttpServletRequest request) {
		Map<?,?> properties = request.getParameterMap();
		Map<String,Object> returnMap = new HashMap<String,Object>();
		Iterator<?> entries = properties.entrySet().iterator();
		Map.Entry<?,?> entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {
			entry = (Map.Entry<?,?>) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if(null == valueObj){
				value = "";
			}else if(valueObj instanceof String[]){
				String[] values = (String[])valueObj;
				for(int i=0;i<values.length;i++){
					value = values[i] + ",";
				}
				value = value.substring(0, value.length()-1);
			}else{
				value = valueObj.toString();
			}
			returnMap.put(name, value);
		}
		return returnMap;
	}

}
